﻿using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Runtime.Serialization;

namespace Honeycomb.Core
{
    /// <summary>
    /// Task implementation.
    /// </summary>
    [Serializable]
    public class TaskBase
    {
        /// <summary>
        /// Deserialises a byte representation of a task to a Task instance.
        /// </summary>
        /// <param name="buffer">Serialized task.</param>
        /// <returns>Deserialized task.</returns>
        public static TaskBase Deserialize(byte[] buffer)
        {
            return Deserialize(buffer, null);
        }

        /// <summary>
        /// Deserialises a byte representation of a task to a Task instance.
        /// </summary>
        /// <param name="buffer">Serialized task.</param>
        /// <param name="binder">Serialization binder.</param>
        /// <returns>Deserialized task.</returns>        
        public static TaskBase Deserialize(byte[] buffer, SerializationBinder binder)
        {
            BinaryFormatter formatter = new BinaryFormatter { Binder = binder };
            return (TaskBase)formatter.Deserialize(new MemoryStream(buffer));
        }

        /// <summary>
        /// Execute method to be executed remotely in the grid.
        /// </summary>
        /// <returns></returns>
        public virtual object Execute()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Serializes a task to a byte array.
        /// </summary>
        /// <returns>Serialized task.</returns>
        public byte[] Serialize()
        {
            MemoryStream memoryStream = new MemoryStream();
            new BinaryFormatter().Serialize(memoryStream, this);
            return memoryStream.GetBuffer();
        }
    }
}